package com.foreknow.dao.impl;


import com.foreknow.dao.GuestbookDao;
import com.foreknow.mapping.EntityMapping;
import com.foreknow.mapping.MappingFactory;
import com.foreknow.model.Admin;
import com.foreknow.model.Guestbook;
import com.foreknow.util.OraclePagination;
import com.foreknow.util.Pagination;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class GuestbookDaoImpl extends BaseDAO implements GuestbookDao {
    @Override
    public boolean addMessage(Guestbook guestbook) throws SQLException {
        String sql = "INSERT INTO guestbook(name,phone,email,title,content,createdtime)VALUES(?,?,?,?,?,?)";
        int  count =  jdbcTemplate.update(sql,guestbook.getName(),guestbook.getPhone(),guestbook.getEmail(),guestbook.getTitle(),guestbook.getContent(), guestbook.getCreatedtime());

        return count==1;
    }

    @Override
    public List<Object> getQueryAll() throws SQLException {
        String sql = "select * from guestbook";
        EntityMapping mapping = this.mappingFactory.getMap(MappingFactory.GUESTBOOK_MAPPING);
        List<Object> list =  this.jdbcTemplate.query(sql,mapping);

        return list;
    }

    @Override
    public boolean updateByid(Guestbook guestbook) throws SQLException {
        boolean isOK=false;

        String sql = "update guestbook set name =?,phone =?,email=?,title=?,content=?,createdtime=? where id =?";
        int count = jdbcTemplate.update(sql,guestbook.getName(),guestbook.getPhone(),guestbook.getEmail(),guestbook.getTitle(),guestbook.getContent(),guestbook.getCreatedtime(),guestbook.getId());
        if(count>0){
                return true;
        }
        return  false;
    }


    @Override
    public Pagination getGuestbookByPage(int pageSize, int pageNumber) throws SQLException {
        String sql = "select * from guestbook";
        Pagination pagination = new OraclePagination(sql,pageSize,pageNumber);
        return pagination;
    }

    @Override
    public Guestbook findAllByid(Integer id) throws SQLException {
        String sql = "select * from guestbook where id = ? ";
        EntityMapping mapping = this.mappingFactory.getMap(MappingFactory.GUESTBOOK_MAPPING);
        List<Object> list= jdbcTemplate.query(sql,mapping,id);
        if(list.size()>0){
            return (Guestbook) list.get(0);
        }else{
            return null;
        }


    }

    @Override
    public boolean deleteByid(Integer id) throws SQLException {

        String sql = "delete from guestbook where id = ?";
        int a =jdbcTemplate.update(sql,id);
        return a==1;
    }
}
